package com.zzw.springboot.config.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zzw.springboot.common.ErrorResult;
import com.zzw.springboot.config.AuthAccess;
import com.zzw.springboot.entity.User;
import com.zzw.springboot.exception.BusinessException;
import com.zzw.springboot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Author zzw2000
 * @Date 2022年05月18日 16:03
 * @Description 描述
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是映射到方法上就直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }else {
            HandlerMethod handlerMethod =(HandlerMethod) handler;
            AuthAccess authAccess = handlerMethod.getMethodAnnotation(AuthAccess.class);
            if (Objects.nonNull(authAccess)){
                return true;
            }
        }
        //获取token
        String token = request.getHeader("token");
        //判断token是否有效
        if (StringUtils.isBlank(token)) {
            throw new BusinessException(ErrorResult.unauthorized());
        }
        //解析token
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException e) {
            throw new BusinessException(ErrorResult.unauthorized());
        }
        User user = userService.getById(userId);
        if (Objects.isNull(user)) {
            throw new BusinessException(ErrorResult.notFoundUser());
        }
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            verifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new BusinessException(ErrorResult.unauthorized());
        }
        //放行
        return true;
    }
}
